//
//  Api.m
//  SSWiFi
//
//  Created by 酷安 @啥也不会啊啊啊啊啊啊  on 2024/3/10.
//

#import "Api.h"
@interface Api()
@property (copy,nonatomic) NSString *band;//当前频段

@end


@implementation Api

- (instancetype)init:(NSDictionary *)serverInfo
{
    self = [super init];
    if (self) {
        self.serverinfo = serverInfo;
    }
    return self;
}

- (NSString *)serverHost{
    NSString *ip = [self.serverinfo objectForKey:@"ip"];
    NSString *url = [NSString stringWithFormat:@"http://%@",ip];
    return url;
}

- (NSString *)devicesName{
    return @"通用";
}
- (WiFiDeviceTypes)deviceType{
    return WiFiDevice_None;
}

- (NSString *)serverHost:(BOOL)isPost{
    NSString *ip = [self.serverinfo objectForKey:@"ip"];
    NSDictionary *pathdic = [self.serverinfo objectForKey:@"path"];
    NSString *pt = [pathdic objectForKey:@"get"];
    if(isPost){
        pt = [pathdic objectForKey:@"set"];
    }
    NSString *getUrl = [NSString stringWithFormat:@"http://%@/%@",ip,pt];
    return getUrl;
}

- (void)loginCallback:(nullable void (^)(bool flag))callback{
    NSString *pwd = [self.serverinfo objectForKey:@"pwd"];
    [self testLogin:[self serverHost:YES] pwd:pwd callback:^(bool flag) {
        [UserConfig shareInstance].isLogin = flag;
        !callback ? : callback(flag);
    }];
}


- (void)getHomeDataCallback:(nullable void (^)(NSArray<HomeItemModel *> *data))callback errorBack:(nullable void (^)(NSError *err))errorBack{
    NSDictionary *para = @{
        @"multi_data":@"1",
        @"cmd": self.homeDataCmdPara,
    };
    MJWeakSelf;
    NSLog(@"getHomeDataCallback");
    [self.manage GET:[self serverHost:NO] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HomeDataModel *homedata = [HomeDataModel yy_modelWithJSON:responseObject];
        
        self.showInfoCount +=1;
        if(self.showInfoCount <= 2){
            [QMUIConsole log:responseObject];
        }
       
//        [self loginChange:homedata.realtime_time.length > 0];
        
        
        //网络提供商 信号
        NSMutableArray *arr = [NSMutableArray array];
        if(homedata.lte_band.length == 0){
            homedata.lte_band = [weakSelf band];
        }
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_Network title:@"" model:homedata]];
        //电池 网络连接
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_NetConnTime title:@"" model:homedata]];
        //IMEI ICCID
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_IMEI title:@"" model:homedata]];
        //流量
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_CurrentUseByte title:@"" model:homedata]];
        //实时网速
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_RealtimeUseByte title:@"实时网速" model:homedata]];
        //统计流量
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_TotalUseByte title:@"流量统计" model:homedata]];
        //WIFI 设置
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_WiFiInfo title:@"WiFi信息" model:homedata]];
        //WIFI 覆盖范围
        [arr addObject:[[HomeItemModel alloc] initType:HomeCellType_WiFiSeting title:@"覆盖范围" model:homedata]];
        
        !callback ? : callback(arr);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [self loginChange:NO];
            [UserConfig shareInstance].isLogin = NO;
            dispatch_after(3, dispatch_get_main_queue(), ^{
                !errorBack ? : errorBack(error);
            });
            
        }];
    [self get_Reside_Band];
    
    
}


/// 首页数据 请求参数
- (NSString *)homeDataCmdPara{
    return @"network_provider,battery_charging,battery_pers,lan_ipaddr,monthly_rx_bytes,monthly_time,monthly_tx_bytes,network_type,realtime_rx_bytes,realtime_rx_thrpt,realtime_time,realtime_tx_bytes,realtime_tx_thrpt,sub_network_type,wifi_cur_state,lte_rsrp,sta_count,imei,SSID1,WPAPSK1_encode,ziccid,wifi_coverage,lte_band,data_volume_limit_size,signalbar,alk_sim_select,sim_current_type,simcard_type,sim_slot";
}



/// 获取京东云频段
- (void)get_Reside_Band{
    NSDictionary *para = @{
        @"cmd":@"GET_RESIDE_BAND",
    };
    MJWeakSelf;
    [self.manage GET:[self serverHost:NO] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *v = [responseObject objectForKey:@"result"];
        NSArray  *vs = [v componentsSeparatedByString:@","];
        if(vs.count == 2){
            weakSelf.band = vs.lastObject;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)rebootCallback:(nullable void (^)(bool flag,NSString*msg))callback{
    NSDictionary *para = @{
        @"goformId": @"REBOOT_DEVICE",
    };
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"重启: %@",responseObject);
        !callback ? : callback(YES,@"重启中..");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"重启: %@",error);
        !callback ? : callback(NO,@"重启失败");
    }];
}


- (void)poweroffCallback:(void (^)(bool flag, NSString * _Nonnull msg))callback{
    NSDictionary *para = @{
        @"goformId": @"TURN_OFF_DEVICE",
    };
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"关机:%@",responseObject);
        !callback ? : callback(YES,[responseObject objectForKey:@"result"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"关机: %@",error);
        !callback ? : callback(NO,error.localizedDescription);
    }];
}


- (void)setWiFiCoveragePara:(NSString *)wifi_coverage callback:(void (^)(bool))callback{
    
    NSDictionary *para = @{
        @"goformId": @"SET_WIFI_COVERAGE",
        @"wifi_coverage": wifi_coverage,
    };
    
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        !callback ? : callback(YES);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !callback ? : callback(NO);
    }];
}

- (void)setWiFiInfoWithSsid:(NSString *)ssid pwd:(NSString *)pwd callback:(void (^)(bool))callback{
    NSDictionary *para = @{
        @"goformId": @"SET_WIFI_SSID1_SETTINGS",
        @"ssid": ssid,
        @"passphrase": [pwd base64],
        @"security_mode": @"WPA2PSK",
        @"security_shared_mode": @"1",
        @"cipher": @"1",
        @"NoForwarding":@"0",
    };
    [self.manage POST: [self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        !callback ? : callback(YES);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !callback ? : callback(NO);
    }];
}

- (void)setUserDataNum:(float)dataNum callback:(void (^)(bool))callback{
    NSDictionary *para = @{
        @"goformId": @"DATA_LIMIT_SETTING",
        @"data_volume_limit_switch": @"1",
        @"data_volume_limit_unit": @"data",
        @"data_volume_limit_size": [NSString stringWithFormat:@"%.2f_1024",dataNum],
        @"data_volume_alert_percent": @"99"
    };
    NSLog(@"%@",para);
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        !callback ? : callback(YES);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !callback ? : callback(NO);
    }];
}

- (void)setUsedata:(float)usedata callback:(void (^)(bool flag,NSString*msg))callback{
    NSDictionary *para = @{
        @"goformId": @"FLOW_CALIBRATION_MANUAL",
        @"calibration_way": @"data",
        @"time": @"0",
        @"data" : [NSString stringWithFormat:@"%.2f@",usedata],
    };
    
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([[responseObject objectForKey:@"result"] isEqualToString:@"success"]){
            !callback ? : callback(YES,@"设置成功");
        }else{
            !callback ? : callback(YES,@"等待页面刷新");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !callback ? : callback(NO,error.localizedDescription);
    }];
}


- (void)setIMEI:(NSString *)imei goformId:(NSString *)goformId callback:(void (^)(NSString *msg))callback{
    NSDictionary *para = @{
//        @"goformId": @"ALK_WRITE_IMEI",
        @"goformId" : goformId,
        @"imei_string": imei,
//        @"goformId": @"SET_IMEI_NUM", //京东云参数
        @"imei": imei, //京东云参数
        
    };
    [self.manage POST:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        !callback ? : callback([responseObject objectForKey:@"result"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !callback ? : callback(error.localizedDescription);
    }];
}

- (void)openAdbCallback:(void (^)(bool flag))callback{
    //goformId=SET_DEVICE_MODE&debug_enable=1
    NSDictionary *para = @{
        @"goformId": @"SET_DEVICE_MODE",
        @"debug_enable": @"1"
    };
    [self.manage GET:[self serverHost:YES] parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSString *value = [responseObject objectForKey:@"result"];
        !callback ? : callback([value containsString:@"successfully"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        !callback ? : callback(NO);
    }];
}



/// 获取支持的频段
/// @param callback callback
- (void)getSupportBandCallBack:(void (^)(NSArray<BandItemModel *> * _Nullable))callback{
    !callback ? : callback(nil);
}


/// 设置频段
/// @param bands 频段
/// @param callback callback
- (void)setBandPara:(NSString *)bands callBack:(void (^)(bool, NSString * _Nonnull))callback{
    !callback ? : callback(NO,@"不支持设置");
}


/// 获取当前选择的频段
/// @param callback callback
- (void)getSelectedBandCallBack:(void (^)(NSString * _Nullable bands))callback{
    !callback ? : callback(nil);
}


- (void)testLogin:(NSString *)url pwd:(NSString *)pwd callback:(void (^)(bool flag))callback{
    NSDictionary *para = @{
        @"goformId": @"LOGIN",
        @"password": [pwd base64]
    };
    [self.manage POST:url parameters:para headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [QMUIConsole logs:@[url,pwd,responseObject]];
        NSString *v = [responseObject objectForKey:@"result"];
        bool flag = [v isEqualToString:@"0"];
        !callback ? : callback(flag);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [QMUIConsole logs:@[url,pwd,error.description]];
        !callback ? : callback(NO);
    }];
}
@end
